<?php

namespace App\Support\Helpers;

use Illuminate\Support\Str as IlluminateStr;

class Str
{
    /**
     * generate random text
     *
     * @param int $length     length of the generated text
     * @param string $pool    character pool
     *
     * @return string  generated random text
     */
    public static function quickRandom($length = 6, $pool = null)
    {
        if (empty($pool)) {
            return IlluminateStr::quickRandom($length);
        }

        $repeats = ceil($length / strlen($pool));
        return substr(str_shuffle(str_repeat($pool, $repeats)), 0, $length);
    }

    /**
     * decode json in a safe way. by 'safe', we mean that false will be safely
     * returned if given json text is invalid.
     *
     * @param string $json the <i>json</i> string being decoded.
     * @param bool $assoc  when <b>TRUE</b>, returned objects will be converted into associative arrays.
     *
     * @return mixed       the decoded value or false on error.
     */
    public static function safeJsonDecode($json, $assoc = true)
    {
        $decoded = json_decode($json, $assoc);
        if ($decoded === null  && json_last_error() !== JSON_ERROR_NONE) {
            return false;
        } else {
            return $decoded;
        }
    }
}
